package SSF.OS.NetFlow.Filter;

import com.renesys.raceway.DML.*;

/**
 * Basically, given a number, it checks whether the number is within a range or not.
 */
public class NumericRange implements Range
{
    double minValue=0;
    double maxValue=0;

    /**
     * config the range, decide the min and max value
     * <UL>
     * <LI> min -- min value
     * <LI> max -- max value
     * </UL>
     */
    public void config(Configuration cfg, byte dataType) throws configException
    {
	//check whether it's one of the suitable data type.
	if (dataType!=Decoder.INT_TYPE 
	    && dataType != Decoder.SHORT_TYPE
	    && dataType != Decoder.BYTE_TYPE
	    && dataType != Decoder.FLOAT_TYPE
	    && dataType != Decoder.LONG_TYPE) {
	    System.err.println("Error in NumericRange.config, the numerice range for the given data type is not defined.");
	    throw new configException("Invalid dataType for NumericRange");
	}
	else {
	    String evals;

	    // get the min value
	    evals = (String)cfg.findSingle("min");
	    if (evals == null) {
		System.err.println("Warning: min value for numeric range is not defined");
		minValue = Double.NEGATIVE_INFINITY;
	    }
	    else
		minValue = Double.valueOf(evals).doubleValue();

	    // get the max value
	    evals = (String)cfg.findSingle("max");
	    if (evals == null) {
		System.err.println("Warning: max value for numeric range is not defined.");
		maxValue = Double.POSITIVE_INFINITY;
	    }
	    else 
		maxValue = Double.valueOf(evals).doubleValue();
	}
    }

    /**
     * check whether given data is within the range
     */
    public boolean inRange(Object data, byte dataType)
    {
	double dData;

	switch (dataType) {
	case Decoder.INT_TYPE:
	    dData = ((Integer)data).doubleValue();
	    break;
	case Decoder.SHORT_TYPE:
	    dData = ((Short)data).doubleValue();
	    break;
	case Decoder.BYTE_TYPE:
	    dData = ((Byte)data).doubleValue();
	    break;
	case Decoder.FLOAT_TYPE:
	    dData = ((Float)data).doubleValue();
	    break;
	case Decoder.LONG_TYPE:
	    dData = ((Long)data).longValue();
	default:
	    System.err.println("Invalid data type in NumericRange.inRange()");
	    return false;
	}

	//for debug
	//System.err.println("data "+dData + " min " + minValue + " max "+ maxValue);
	return dData >= minValue && dData <= maxValue;
    }
}
